package com.byx.chatclient.im;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;

import com.byx.chatclient.ChatApp;
import com.byx.imclientutil.entity.MessageType;
import com.byx.imclientutil.listener.OnApplicationLayerCallBack;
import com.byx.imclientutil.listener.OnMessageStatusListener;
import com.byx.imclientutil.protobuf.ChatMessageProtobuf;

import java.util.UUID;

/**
 * ImEventListener
 *
 * @author Superb
 * @date 2021/4/5 10:20
 */
public class ImEventListener implements OnApplicationLayerCallBack {
    private final String userId;

    public ImEventListener(String userId) {
        this.userId = userId;
    }

    /**
     * 分发消息到应用层
     *
     * @param msg
     */
    @Override
    public void dispatchMessage(ChatMessageProtobuf.Msg msg) {
        MessageProcessor.getInstance().receiveMsg(MessageConverter.toBaseMessage(msg));
    }

    /**
     * 从应用层获取网络是否可用
     *
     * @return
     */
    @Override
    public boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) ChatApp.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
        Network network =connectivityManager.getActiveNetwork();
        if(network!=null){
            NetworkCapabilities nc=connectivityManager.getNetworkCapabilities(network);
            if(nc!=null){
                if(nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)){
                    //WIFI
                    return true;
                }else if(nc.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)){
                    //移动数据
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取由应用层构造的握手消息
     *
     * @return
     */
    @Override
    public ChatMessageProtobuf.Msg getHandshakeMsg() {
        return ChatMessageProtobuf.Msg.newBuilder()
                .setMessageId(UUID.randomUUID().toString())
                .setMessageType(MessageType.HAND_SHAKE_MSG)
                .setFromId(userId)
                .setTimestamp(System.currentTimeMillis())
                .build();
    }

    /**
     * 获取由应用层构造的心跳消息
     *
     * @return
     */
    @Override
    public ChatMessageProtobuf.Msg getHeartbeatMsg() {
        return ChatMessageProtobuf.Msg.newBuilder()
                .setMessageId(UUID.randomUUID().toString())
                .setMessageType(MessageType.HEART_BEAT_MSG)
                .setFromId(userId)
                .setTimestamp(System.currentTimeMillis())
                .build();
    }

    /**
     * 获取应用层消息发送状态报告消息类型
     *
     * @return
     */
    @Override
    public int getServerSentReportMsgType() {
        return MessageType.SERVER_STATUS_REPORT;
    }

    /**
     * 获取应用层消息接收状态报告消息类型
     *
     * @return
     */
    @Override
    public int getClientReceivedReportMsgType() {
        return MessageType.CLIENT_STATUS_REPORT;
    }
}
